
import { UserTypes } from "../types/userTypes"
import { Credentials } from "../reducers/userReducer"
import { UserActions } from "../actions/userActions" 
import { ThunkAction } from "redux-thunk"
import { AppState } from "@src/index"
import { userInfoRequest } from "@src/requests/user"
import { AxiosError } from "axios"


export namespace UserCreators{
    //用于返回保存用户登录凭据的action  creator函数
    export const saveCredentials = (credentials:Credentials):UserActions.SaveCredentials => ({
        type:UserTypes.SAVE_CREDENTIALS,
        payload:credentials
    })
    //获取管理员信息
    export const requestUserInfo= ():ThunkAction<Promise<UserActions.Actions>,AppState,any,UserActions.Actions>  => async (dispatch)=>{
        //更新请求状态
        dispatch({type:UserTypes.REQUEST_USER_INFO})
        //捕获错误
        try{
            //发送请求
         const response =  await userInfoRequest()
         //保存请求结果 更新请求状态
        return dispatch({type:UserTypes.REQUEST_USER_INFO_SUCCESS,payload:response.data})
        }catch(error){
                // 保存请求失败信息
        if (error instanceof AxiosError) {
            return Promise.reject(
              dispatch({
                type: UserTypes.REQUEST_USER_INFO_ERROR,
                error: error.response?.data.message,
              })
            );
          }
          // 抛出异常
          return Promise.reject(error);
        }
    }

    //清空用户信息
    export const clearUser = ():UserActions.Actions =>({
      type:UserTypes.CLEAR_USER
    })
}